from datetime import date

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAdminUser

from apps.goods.models import GoodsVisitCount
from apps.users.models import User
from datetime import timedelta
from apps.meiduo_admin.serializers.home import UserCategoryCountSerializer


class UserTotalCountAPIView(APIView):

    # 设置权限访问
    permission_classes = [IsAdminUser]
    def get(self, request):
        count = User.objects.all().count()
        return Response({'count': count})

# 日增用户统计
class UserDailyCountView(APIView):

    permission_classes = [IsAdminUser]
    def get(self, request):
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()
        return Response({'count': count})

# 日活跃用户统计
class UserDailyActiveCountView(APIView):

    permission_classes = [IsAdminUser]
    def get(self, request):
        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()
        return Response({'count': count})

# 日下单用户量统计
class UserDailyOrderCountView(APIView):

    permission_classes = [IsAdminUser]
    def get(self, request):
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()
        return Response({'count': count})

# 月增用户统计
class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self, request):
        today = date.today()
        start_date = today - timedelta(days=30)
        date_list = []
        for i in range(31):
            count = User.objects.filter(date_joined__gte=start_date, date_joined__lt=start_date + timedelta(days=1)).count()
            date_list.append(
                {
                    'date': start_date,
                    'count': count
                }
            )

            start_date = start_date + timedelta(days=1)
        return Response(date_list)

# 日分类商品访问量
class UserCategoryCountAPIView(APIView):

    permission_classes = [IsAdminUser]
    def get(self, request):

        today = date.today()
        data = GoodsVisitCount.objects.filter(date__gte=today)
        # 准备序列化器
        serializer = UserCategoryCountSerializer(data, many=True)
        # 返回字典列表
        return Response(serializer.data)